package com.itany.corejava.code16_反射;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author MissChen
 * @date 2024年03月26日 14:21
 */
public class Test04_Field {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = User.class;
        // 1.获取当前类以及其父类中所有public修饰的属性
        Field[] fields = c.getFields();
        System.out.println(Arrays.toString(fields));

        // 2.获取当前类中所有的属性,不区分修饰符
        Field[] declaredFields = c.getDeclaredFields();
        System.out.println(Arrays.toString(declaredFields));

        // 3.获取当前类以及其父类中指定的由public修饰的属性
        // 如果属性是被private修饰的,则报错
        Field usernameField = c.getField("username");
        System.out.println(usernameField);

        //如果属性是被private修饰的,则报错
        // Field passwordField=c.getField("password");
        // System.out.println(passwordField);

        //获取父类中的public修饰的属性
        Field ageField = c.getField("age");
        System.out.println(ageField);

        // 4.获取当前类中指定的属性,不区分修饰符
        // 无法获取父类的属性,报错

        Field passwordField = c.getDeclaredField("password");
        System.out.println(passwordField);

        //无法获取父类的属性,报错
        // Field nameField=c.getDeclaredField("name");
        // System.out.println(nameField);
        User user = new User();
        usernameField.set(user, "admin");
        usernameField.set(user, "tom");
        System.out.println(user);

        //不能访问private修饰的属性
        // passwordField.set(user,"123");
        // System.out.println(user);

        String username = (String) usernameField.get(user);
        System.out.println(username);

        //不能访问private修饰的属性
        // String password= (String) passwordField.get(user);
        // System.out.println(password);

        passwordField.setAccessible(true);
        passwordField.set(user, "123");
        System.out.println(user);
        String password= (String) passwordField.get(user);
        System.out.println(password);
    }
}
